package com.ch.ms.server.base;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.internal.logging.InternalLoggerFactory;
import io.netty.util.internal.logging.Slf4JLoggerFactory;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.util.UUID;

@Slf4j
@Data
public abstract class AbstractMapleServer implements MapleServer {

    @Getter
    @Builder.Default
    private String id = UUID.randomUUID().toString();


    @Getter(AccessLevel.NONE)
    @Setter(AccessLevel.NONE)
    private ServerBootstrap serverBootstrap;

    @Getter(AccessLevel.NONE)
    @Setter(AccessLevel.NONE)
    private EventLoopGroup bossGroup;

    @Getter(AccessLevel.NONE)
    @Setter(AccessLevel.NONE)
    private EventLoopGroup workerGroup;

    @Getter(AccessLevel.NONE)
    @Setter(AccessLevel.NONE)
    private ChannelFuture channelFuture;

    public AbstractMapleServer() {
        InternalLoggerFactory.setDefaultFactory(new Slf4JLoggerFactory());
        bossGroup = new NioEventLoopGroup(1);
        workerGroup = new NioEventLoopGroup();
        serverBootstrap = new ServerBootstrap()
                .group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO));
                        ch.pipeline().addLast(new MaplePacketDecoder(getSupportedPackets()));
                        ch.pipeline().addLast(new MaplePacketEncoder());
                        ch.pipeline().addLast(new MapleServerHandler(getPacketHandlers()));

                        if (!CollectionUtils.isEmpty(getChannelHandlers()))
                            ch.pipeline().addLast(getChannelHandlers().toArray(new ChannelHandler[]{}));
                    }
                });
    }


    @Override
    public boolean bind(String host, int port) {
        boolean result = false;
        log.info("正在尝试将{}绑定到主机{}上的端口{}", getName(), host, port);
        channelFuture = serverBootstrap.bind(host, port);
        try {
            result = channelFuture.sync().isSuccess();
            log.info("绑定{}", result ? "成功" : "失败");

            if (result) afterBind();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return result;
    }

    public void afterBind() {
    }

    @Override
    public boolean shutdown() {
        boolean result = false;
        log.info("正在关闭{}", getName());
        try {
            result = channelFuture.channel().close().sync().isSuccess() && bossGroup.shutdownGracefully().sync().isSuccess()
                    && workerGroup.shutdownGracefully().sync().isSuccess();
            log.info("关闭{}", result ? "成功" : "失败");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return result;
    }
}
